<?php

class DB {

	private $handle = null;
	private static $instance = null;

	private function __construct($dbName, $method = 'open') {
		$path = ROOT . '/../../sqlite/' . $dbName . '.db';

		if (!is_writable($path)) {
			echo $path . ' can\'t writeable';
		}

		if ($method == 'open') {
			if (!file_exists($path)) {
				exit('db not exists!');
			}
		}

		if ($method == 'create') {
			if (file_exists($path)) {
				unlink($path);
			}
		}

		$this->handle = sqlite_open($path);

		sqlite_create_function('now', 'sqliteNow');
	}

	public static function create($dbName) {
		if (!(self::$instance instanceof self)) {
			self::$instance = new self($dbName, 'create');
		}

		return self::$instance;
	}

	public static function open($dbName) {
		if (!(self::$instance instanceof self)) {
			self::$instance = new self($dbName);
		}

		return self::$instance;
	}

	public function query($sql, $mode = SQLITE_ASSOC) {
		$data = array();
		if (($result = sqlite_query($this->handle, $sql, $mode))) {
			while ($row = sqlite_fetch_object($result)) {
				array_push($data, $row);
			}
		}

		return $data;
	}

	public function find($sql) {
		$data = $this->query($sql);
		return isset($data[0]) ? $data[0] : false;
	}

	public function exec($sql) {
		if (sqlite_exec($this->handle, $sql)) {
			return true;
		} else {
			echo $sql;
			exit(0);
		}
	}

	public function __destroy() {
		sqlite_close($this->handle);
	}

}